# 02 C++多线程笔记 ## 2.1 基础锁类型 1. mutex 2. timed_mutex 3. recursive_mutex 4. recursive_timed_mutex 5. shared_timed_mutex 6. shared_mutex 基础接口:上面所有mutex都支持 mutex.lock() 独占锁 mutex.unlock() 释放独占锁 mutex.try_lock() 尝试获取独占锁,如果获取锁失败,不阻塞,返回false 时间mutex接口:(timed_mutex, recursive_timed_mutex, shared_timed_mutex) try_lock_for(std::chrono::milliseconds(100)) 传入一个时间段 auto deadline = steady_clock::now() + milliseconds(50); try_lock_until(deadline) 传入一个时间点 共享锁接口:(shared_mutex, shared_timed_mutex) mutex.lock_shared() 获取共享锁 mutex.try_lock_shared() 尝试获取共享锁 mutex.unlock_shared() 释放共享锁 ## 2.2 常见的锁RAII包装器 1. lock_guard: 基础的构造时获取锁,析构时释放锁; lock_guard(mutex, adopt_lock),表示当前线程已经具备锁在构造的时候不获取锁; 2. unique_lock: 也是构造时获取锁,析构时释放锁; 3. shared_lock: 入参必须是shared_mutex或者,shared_timed_mutex,其主要用于管理共享锁获取和释放; 注意shared_lock.lock方法底层调用的是shared_mutex.lock_shared接口。 4. scoped_lock: 主要用于多个mutex锁定,避免顺序不一致造成死锁,lock_guard类似,也支持adopt_lock策略; ```{note} **std::lock_guard VS std::unique_lock** **相同点:** std::unique_lock的基础功能和std::lock_guard一致,默认在构造时获取锁,析构的时候释放锁; 并且都支持adopt_lock策略,表示当前线程已经获得锁,在构造的时候不用重复获取,只需要在析构的时候释放锁; **差异点:** 首先std::unique_lock不能复制,但是可以移动出函数,而lock_guard不允许复制和移动; 其次,std::unique_lock除了默认的锁获取策略和adopt_lock之外,还支持defer_lock, try_to_lock策略, 而lock_guard不支持这两种策略; defer_lock 表示需要用户手动获取lock,并且可以在销毁前手动释放lock,当然用户没有手动释放,析构的时候也会安全释放; 其三,std::unique_lock支持和condition_variable进行条件等待和判断; **底层实现和效率差异:** std::lock_guard 是低成本抽象,占用任何额外的成员变量内存最小(内部仅持有互斥量的引用); std::unique_lock 内部会多维护一个 bool 类型的标志位(用于记录当前是否持有锁), 以支持手动 unlock()/lock() 以及 try_to_lock 等灵活操作,因此存在极微小的空间和性能开销。 ``` ```C++ #include #include #include std::mutex mt; float data = 0.0; std::condition_variable cv; void func_in_thread1(){ std::unique_lock lock(mt); cv.wait_for(lock, []{return data > 100;}); // do something with lock } void func_in_thread(){ std::lock_guard l(mt); // do something with lock } ``` ## 2.3 条件语法 1. `condition_variable`: 只支持此`std::unique_lock` 2. `condition_variable_any`:支持所有实现`BasicLockable`接口的对象,具备`lock,unlock`方法; + wait(lock) + wait_for(lock, timeout, func) + wait_until(timepoint) ```{note} 在操作系统的线程调度中,存在一个Runqueue线程列表,mutex.lock会,cv.wait底层操作系统通常会将阻塞线程从可运行队列转入等待队列; mutex.lock的目的是用于一个信号限制竞争资源的争夺,condition_variable这是用一个信号限制线程的运行,满足特定条件的时候才能运行; condition_variable条件内容也是一个竞争资源,所以condition_variable需要一个mutex进行锁定,确保睡眠等待和满足条件执行成为严格的互斥; 所以condition_variable必须要使用一个mutex; 底层的mutex才是严格意义上的锁元语,lock_guard, unique_lock, shared_lock, scoped_lock 只是在mutex基础上的常见锁定模式封装。 shared_lock.lock实现的是共享锁定,常用于读写锁的读模式(其底层调用的是shared_mutex.lock_shared), 如果要实现读写锁的写模式,则需要使用同一个mutex,采用unique_lock封装。 多线程编程中最核心的一个点,就是要分析出有哪些竞争资源, 确保合适的锁定范围, 有哪些运行条件,避免死锁(顺序不一致多个锁定,未释放死锁等) ``` ## 2.4 多线程异步元语 ### 2.4.1 `promise`和`future` promise表示将来可能在其他某个地方会发送一个数据或者个异常,future表示将来可以获取一个结果或者异常; 逻辑上promise是数据的产生者(其他线程或者协程),future是数据的消费者,两者是同一个数据两种视角的不同表述; 所以promise和future都是成对出现的一一对应的(C++内置的某些接口直接返回future是因为接口内部封装,让用户省略了promise的创建); ### 2.4.1.1 `shared_future` `std::future` 只能被移动,且 `get()` 只能调用一次;`std::shared_future` 是它的共享版本,可以复制给多个消费者,多次调用 `get()` 读取同一个结果。 适合的场景: 1. 一个异步结果需要被多个线程同时读取。 2. 一个初始化结果需要广播给多个后续任务。 常见用法:先通过 `future.share()` 把 `future` 转成 `shared_future`,或者直接用 `std::shared_future` 接收结果。 ```C++ #include #include #include int compute_value() { return 42; } void print_value(std::shared_future value) { std::cout << value.get() << '\n'; } int main() { std::future future = std::async(std::launch::async, compute_value); std::shared_future shared = future.share(); std::thread t1(print_value, shared); std::thread t2(print_value, shared); std::cout << shared.get() << '\n'; t1.join(); t2.join(); } ``` ```C++ #include #include #include #include #include #include void accumulate(std::vector::iterator first, std::vector::iterator last, std::promise accumulate_promise) { int sum = std::accumulate(first, last, 0); accumulate_promise.set_value(sum); // Notify future } void do_work(std::promise barrier) { std::this_thread::sleep_for(std::chrono::seconds(1)); barrier.set_value(); } int main() { // Demonstrate using promise to transmit a result between threads. std::vector numbers = {1, 2, 3, 4, 5, 6}; std::promise accumulate_promise; std::future accumulate_future = accumulate_promise.get_future(); std::thread work_thread(accumulate, numbers.begin(), numbers.end(), std::move(accumulate_promise)); // future::get() will wait until the future has a valid result and retrieves it. // Calling wait() before get() is not needed // accumulate_future.wait(); // wait for result std::cout << "result=" << accumulate_future.get() << '\n'; work_thread.join(); // wait for thread completion // Demonstrate using promise to signal state between threads. std::promise barrier; std::future barrier_future = barrier.get_future(); std::thread new_work_thread(do_work, std::move(barrier)); barrier_future.wait(); new_work_thread.join(); } ``` ```{warning} C++11 头文件中的 std::promise / std::future 在设计核心目标就是在线程之间传递异步计算结果,并提供阻塞等待机制。 它的 get() 接口是线程阻塞式(Thread-Blocking)的。 如果在单线程环境中,数据还没准备好你就调用了 future.get(),整个操作系统线程就会被挂起(移出 Runqueue)。 由于同一个线程里后续写数据的代码根本没有机会执行,这直接就会导致线程内部的死锁。 ``` ### 2.4.2 `packaged_task` 和 `async` std::packaged_task是一个模板类,可以将可执行对象lambda, 函数,封装了operator()方法的对象等再封装称一个对象, 该模板类的对象,可以被调用(一般使用场景是std::move传入其他线程),也可以通过get_future()得到一个future对象获取结果; async是一个函数,其有两个重载版本 ```C++ template< class F, class... Args > std::future async( F&& f, Args&&... args ); template< class F, class... Args > std::future async( std::launch policy, F&& f, Args&&... args ); ``` 其返回的都是一个future对象,std::launch是一个枚举类,有两个场景:`std::launch::async | std::launch::deferred`, `std::launch::async`表示自动开启线程,后者表示自动延迟执行; `std::launch::deferred`表示需要延迟模式,表示在future.get/future.wait的时候再计算; ```{warning} std::future 内部持有一个指向 shared state 的 _M_state,future 本身只是访问共享状态的句柄。 shared state 根据不同启动策略具有不同实现: std::launch::async: 创建后台执行任务,shared state 初始为未完成状态;调用 future.get() 时,如果结果未产生,则阻塞当前线程等待 shared state 变为 ready。 std::launch::deferred: shared state 保存待执行函数,不创建线程;第一次调用 get() 或 wait() 时,在当前线程执行函数,完成后将状态变为 ready 并返回结果。 future 的模板参数主要用于确定结果类型,而 async/deferred 行为主要由 shared state 的具体实现决定 ``` ### 2.4.3 `call_once` 和 `once_flag` `std::call_once` 用于保证某段初始化逻辑只执行一次,`std::once_flag` 是配套的标记对象。 常见场景: 1. 单例对象的线程安全初始化。 2. 全局资源、配置表、日志系统的惰性初始化。 3. 只允许执行一次的注册逻辑。 基本形式: ```C++ #include #include #include #include std::once_flag init_flag; void init_once() { std::cout << "init only once" << std::endl; } void worker() { std::call_once(init_flag, init_once); } int main() { std::vector threads; for (int i = 0; i < 4; ++i) { threads.emplace_back(worker); } for (auto &t : threads) { t.join(); } } ``` 补充说明: 1. `once_flag` 不能复制,也不需要手动 reset。 2. `call_once` 传入的初始化函数如果抛异常,下一次调用还会继续尝试执行。 3. 如果初始化逻辑本身依赖锁,建议保持它足够短,避免把复杂业务塞进一次性初始化里。